<?php

class Silk_Zgb_Model_Warehouse extends Mage_Core_Model_Abstract
{
    protected function _construct(){

       $this->_init("zgb/warehouse");

    }

    public function toOptionArray()
    {
    	//$_collection = $this->getCollection();
        $zgb = Mage::helper('zgb');
        $session = Mage::getSingleton('admin/session');
        $roleId = $session->getUser()->getRoleId();
        $user = $session->getUser();

        $where = "";
        if($roleId == $zgb->getRoleId('dealer'))
        {
            $dealer = Mage::getModel('zgb/dealer')->loadByAdminId($user->getId());
            //if($dealer && $dealer->getId())
            //{
            //    $_collection->addFieldToFilter('dealer_id', array('eq'=>$dealer->getId()));
            //}
            $where = " and dealer_id='{$dealer->getId()}'";
        }
        
        if($roleId == $zgb->getRoleId('warehouse'))
        {
            $warehouse = Mage::getModel('zgb/warehouse')->loadByAdminId($user->getId());
            // if($warehouse && $warehouse->getId())
            // {
            //     $_collection->addFieldToFilter('id', array('eq'=>$warehouse->getId()));
            // }
            $where = " and id='{$warehouse->getId()}'";
        }

        $resource = Mage::getSingleton('core/resource');
        $db = $resource->getConnection('core_read');
        $sql = "SELECT id,`name` FROM zgb_warehouse WHERE 1 {$where} ORDER BY CONVERT( `name` USING gbk ) COLLATE gbk_chinese_ci ASC";
        $query = $db->query($sql);
        $_items = $query->fetchAll();

        $_options = array();
        foreach($_items as $_item)
        {
            $_options[] = array('value'=>$_item['id'],'label'=>$_item['name']);
        }
        return $_options;
    }

    public function loadByAdminId($id)
    {
        $collection = $this->getCollection();
        $collection->addFieldToFilter('admin_id', array('eq'=>$id));
        return $collection->getFirstItem();
    }

    public function getWebsiteId()
    {
        $collection = Mage::getModel('core/website')->getCollection()->addFieldToFilter('area_id', array('eq'=>$this->getAreaId()));
        $website = $collection->getFirstItem();
        if($website && $website->getId())
        {
            return $website->getId();
        }
        return 0;
    }

    public function getProductIds()
    {
        $sql = "SELECT entity_id FROM `catalog_product_entity_int` WHERE attribute_id=137 AND VALUE='{$this->getId()}'";
        $resource = Mage::getSingleton('core/resource');
        $db = $resource->getConnection('core_read');
        $query = $db->query($sql);

        $items = $query->fetchAll();
        $ids = array();
        foreach($items as $item)
        {
            $ids[] = $item['entity_id'];
        }
        return $ids;
    }

}
	 